package handlers

import (
	"encoding/json"
	"fast-logistics/cache"
	"fast-logistics/model"
	"fast-logistics/pkg"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "redis_err_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误3次，禁止登录",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username =?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询用户失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "账户或者密码错误",
		})
		return
	}
	if user.Password != pkg.Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

func AddUserNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func UserRole(c *gin.Context) {
	uid := c.Query("uid")
	var role []model.Role
	/*
		SELECT * FROM roles
		LEFT JOIN user_roles ON user_roles.rid=roles.id
		WHERE user_roles.uid=1
	*/
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid=roles.id").
		Where("user_roles.uid = ?", uid).
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
}

func UserNode(c *gin.Context) {
	rid := c.Query("rid")
	var node []model.Node
	/*
		SELECT * FROM nodes
		LEFT JOIN role_nodes ON role_nodes.nid=nodes.id
		WHERE role_nodes.rid=1
	*/
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid=nodes.id").
		Where("role_nodes.rid = ?", rid).
		Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})
}

func AddRepo(c *gin.Context) {
	repo_code := c.PostForm("repo_code")
	repo_name := c.PostForm("repo_name")
	repo_num, _ := strconv.Atoi(c.PostForm("repo_num"))
	data := model.Repo{
		RepoCode: repo_code,
		RepoName: repo_name,
		RepoNum:  repo_num,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func AddRepoOrder(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	order_code := c.PostForm("order_code")
	order_name := c.PostForm("order_name")
	order_from := c.PostForm("order_from")
	data := model.RepoOrder{
		Rid:       rid,
		OrderCode: order_code,
		OrderName: order_name,
		OrderFrom: order_from,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	var list []model.RepoOrderList
	redis_key := "redis_list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("repo_orders").
			Select(
				"repo_orders.id as OrderId",
				"repos.repo_code as RepoCode",
				"repos.repo_name as RepoName",
				"repos.repo_num as RepoNum",
				"repo_orders.order_code as OrderCode",
				"repo_orders.order_name as OrderName",
				"repo_orders.order_from as OrderFrom",
			).
			Joins("LEFT JOIN repos ON repo_orders.rid=repos.id").
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	/*
		SELECT
		repo_orders.id as OrderId,
		repos.repo_code as RepoCode,
		repos.repo_name as RepoName,
		repos.repo_num as RepoNum,
		repo_orders.order_code as OrderCode,
		repo_orders.order_name as OrderName,
		repo_orders.order_from as OrderFrom
		FROM
		repo_orders
		LEFT JOIN repos ON repo_orders.rid=repos.id
	*/

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}

func Deatil(c *gin.Context) {
	id := c.Query("id")
	var det model.RepoOrderList
	/*
		SELECT
		repo_orders.id as OrderId,
		repos.repo_code as RepoCode,
		repos.repo_name as RepoName,
		repos.repo_num as RepoNum,
		repo_orders.order_code as OrderCode,
		repo_orders.order_name as OrderName,
		repo_orders.order_from as OrderFrom
		FROM
		repo_orders
		LEFT JOIN repos ON repo_orders.rid=repos.id
		WHERE repo_orders.rid=1
	*/
	redis_key := "redis_detail_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("repo_orders").
			Select(
				"repo_orders.id as OrderId",
				"repos.repo_code as RepoCode",
				"repos.repo_name as RepoName",
				"repos.repo_num as RepoNum",
				"repo_orders.order_code as OrderCode",
				"repo_orders.order_name as OrderName",
				"repo_orders.order_from as OrderFrom",
			).
			Joins("LEFT JOIN repos ON repo_orders.rid=repos.id").
			Where("repo_orders.rid = ?", id).
			Find(&det)
		jsonData, _ := json.Marshal(det)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &det)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": det,
	})
	return
}
